﻿<!DOCTYPE html>
<html lang="en">
<head>
    <base href="/" />
    <HeadOutlet />
</head>
<body>
    <Routes />
    <script src="_framework/blazor.web.js"></script>
    <script>
        const { fetch: originalFetch } = window;

        window.fetch = async (...args) => {
            const [url, options = {}] = args;

            /*
            https://github.com/dotnet/aspnetcore/blob/c53f7e474ba80124fb9134ebf23d1d626a19b458/src/Components/Web.JS/src/Services/NavigationEnhancement.ts#L34
            https://github.com/dotnet/aspnetcore/blob/c53f7e474ba80124fb9134ebf23d1d626a19b458/src/Components/Web.JS/src/Services/NavigationEnhancement.ts#L192
            https://github.com/dotnet/aspnetcore/issues/53887
            https://github.com/dotnet/aspnetcore/issues/55119
            https://github.com/dotnet/aspnetcore/issues/52412
            Blazor makes js fetch request for Enhance Navigation
            and adds an accept header with the value 'text/html; blazor-enhanced-nav=on'
            So we can intercept all the fetch requests and check if it has an accept header with 'blazor-enhanced-nav' in its value
            */
            let isEnhancedNavRequest = false;
            if (options.headers && options.headers['accept'] && options.headers['accept'].includes('blazor-enhanced-nav')) {
                isEnhancedNavRequest = true;
            }

            if (isEnhancedNavRequest) {
                let beforeEnhancedFetchEvent = new CustomEvent("fluentcms:beforeenhanced", { bubbles: true, detail: { options: options, url: url } });
                document.dispatchEvent(beforeEnhancedFetchEvent);
            }

            const response = await originalFetch(...args);

            // if (isEnhancedNavRequest) {
            //     const responseContentType = response.headers.get('content-type');
            //     if (responseContentType?.startsWith('text/html')) {
            //         let afterEnhancedFetchEvent = new CustomEvent("fluentcms:afterenhanced", { bubbles: true, detail: response });
            //         document.dispatchEvent(afterEnhancedFetchEvent);
            //     }
            // }

            return response;
        }

        let initEvent = new CustomEvent("fluentcms:init", { bubbles: true });
        document.dispatchEvent(initEvent);

        Blazor.addEventListener('enhancedload', () => {
            let initEvent = new CustomEvent("fluentcms:afterenhanced", { bubbles: true });
            document.dispatchEvent(initEvent);
        })
    </script>
</body>
</html>
@code {

    // app is static (NoneInteractive) only so we don't need to null check out HTTP Context
    [CascadingParameter]
    private HttpContext? HttpContext { get; set; } = default!;
}
